package com.zhoupeisen.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.zhoupeisen.entity.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @ClassName OrderController
 * @Description TODO
 * @Author Administrator
 * @Data 下午 03:52
 * @Version 1.0
 **/
@RestController
@RequestMapping("/order")
@DefaultProperties(defaultFallback = "defaultOrderFallBack")
public class OrderController {
    @Autowired
    DiscoveryClient discoveryClient;
    @Autowired
    RestTemplate restTemplate;

    @HystrixCommand
    @RequestMapping(value = "/buy/{id}",method = RequestMethod.GET)
    public Product findById(@PathVariable Long id){
        List<ServiceInstance> productServices = discoveryClient.getInstances("productService");
        if(null != productServices && productServices.size() > 0) {
            ServiceInstance serviceInstance = productServices.get(0);
            System.out.println(serviceInstance.getHost());
            System.out.println(serviceInstance.getPort());
            System.out.println(serviceInstance.getUri());
        }
        Product product = null;
//      使用了 @LoadBalance注解之后   必须要用 （productService）服务名的方式访问

        product = restTemplate.getForObject("http://productService/product/1", Product.class);
        System.out.println(product);
        return product;
    }


    // 类下降级方法    此方法必须无参数
    public Product defaultOrderFallBack(){
        Product product = new Product();
        product.setProductName("触发了统一熔断器方法");
        return product;
    }

// 降级方法
    public Product orderFallBack(Long id){
        Product product = new Product();
        product.setProductName("出发了熔断器");
        return product;
    }
}
